package com.zhangxun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangxun.domain.SysUser;
import com.zhangxun.domain.SysUserRole;
import com.zhangxun.mapper.SysUserRoleMapper;
import com.zhangxun.service.SysUserService;
import com.zhangxun.mapper.SysUserMapper;
import com.zhangxun.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @author 张循
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2022-12-29 15:29:14
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Page<SysUser> userPage(Page<SysUser> page, SysUser sysUser) {
        return sysUserMapper.selectPage(page,
                new LambdaQueryWrapper<SysUser>().like(StringUtils.hasText(sysUser.getUsername()),
                        SysUser::getUsername, sysUser.getUsername()));
    }

    /**
     * 保存新增管理员的信息和角色信息
     * @param sysUser 接收的用户数据
     * @return 返回是否保存成功
     */
    @Override
    public boolean saveUserAndRoleId(SysUser sysUser) {

        //保存管理员信息
        sysUser.setCreateTime(new Date()); //设置创建时间
        sysUser.setCreateUserId(SecurityUtil.getUserId()); //创建者的id
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));//密码加密
        sysUserMapper.insert(sysUser); //保存

        //通过用户的角色id保存角色信息保存到用户角色中间表
        sysUser.getRoleIdList().stream().forEach(roleId->{
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRoleMapper.insert(sysUserRole);
        });

        return true;
    }

    /**
     * 修改用户信息和用户的角色信息
     * @param sysUser 封装用户信息和角色信息的对象
     * @return 返回是否修改成功
     */
    @Override
    @Transactional
    public boolean updateUserAndRoleId(SysUser sysUser) {
        //密码加密
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        //保存修改的用户信息
        sysUserMapper.updateById(sysUser);

        //删除用户之前的角色信息
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",sysUser.getUserId());
        sysUserRoleMapper.delete(wrapper);

        //添加用户新的角色信息
        sysUser.getRoleIdList().stream().forEach(roleId->{
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(sysUser.getUserId());
            userRole.setRoleId(roleId);

            sysUserRoleMapper.insert(userRole);
        });

        return true;

    }

    /**
     * 修改密码
     * @param sysUser 保存用户输入的旧密码和新密码
     * @return
     */
    @Override
    public boolean updatePasswordById(SysUser sysUser) {

        //获取当前用户对象，判断输入的密码是否正确，正确就修改密码
        Long userId = SecurityUtil.getUserId();
        SysUser user = sysUserMapper.selectById(userId);
        boolean isMatches = passwordEncoder.matches(sysUser.getPassword(), user.getPassword());
        if(isMatches) {
            //修改密码
            user.setPassword(passwordEncoder.encode(sysUser.getNewPassword()));
            sysUserMapper.updateById(user);

            //删除redis当中的token
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");
            isMatches = stringRedisTemplate.delete(authorization);
        }
        return isMatches;
    }
}




